package org.example.test.test;

import java.util.Objects;

/**
 * 最长公共前缀
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 * 如果不存在公共前缀，返回空字符串 ""。
 * 输入：strs = ["flower","flow","flight"]
 * 输出："fl"
 */
public class LongestCommonPrefix {
    public static void main(String[] args) {
        String[] arr = {"flower","flow","flight"};
        System.out.println(longestCommonPrefix(arr));
    }
    public static String longestCommonPrefix(String[] strs){
        String returnStr = strs[0];
        for (int i = 1; i <= strs.length - 1; i++) {
            returnStr = getStr(returnStr, strs[i]);
            if (Objects.equals(returnStr, "")) {
                return "";
            }
        }
        return returnStr;
    }

    public static String getStr(String s1, String s2) {
        if (Objects.equals(s1, "") || Objects.equals(s2, "")) {
            return "";
        }
        String s = s1.length() < s2.length() ? s1 : s2;
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (s1.charAt(i) == s2.charAt(i)) {
                stringBuilder.append(s1.charAt(i));
            } else {
                return stringBuilder.toString();
            }
        }
        return stringBuilder.toString();
    }

}
